<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="柜号" prop="deviceGridName">
            <el-input v-model="queryParams.deviceGridName" placeholder="请输入柜号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="设备号" prop="deviceNo">
            <el-input v-model="queryParams.deviceNo" placeholder="请输入设备号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="订单编号" prop="orderNo">
            <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
<!--          <el-form-item label="开始时间" prop="startTime">-->
<!--            <el-date-picker clearable-->
<!--              v-model="queryParams.startTime"-->
<!--              type="date"-->
<!--              value-format="YYYY-MM-DD"-->
<!--              placeholder="请选择开始时间"-->
<!--            />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="结束时间" prop="endTime">-->
<!--            <el-date-picker clearable-->
<!--              v-model="queryParams.endTime"-->
<!--              type="date"-->
<!--              value-format="YYYY-MM-DD"-->
<!--              placeholder="请选择结束时间"-->
<!--            />-->
<!--          </el-form-item>-->
          <el-form-item label="订单状态" prop="orderStatus">
            <el-select v-model="queryParams.orderStatus" placeholder="请选择状态" clearable>
              <el-option
                v-for="dict in order_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="押金状态" prop="refundStatus">
            <el-select v-model="queryParams.refundStatus" placeholder="请选择状态" clearable>
              <el-option
                v-for="dict in refund_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="结算状态" prop="settlementStatus">
            <el-select v-model="queryParams.settlementStatus" placeholder="请选择状态" clearable>
              <el-option
                v-for="dict in order_settlement_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
<!--          <el-col :span="1.5">-->
<!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['device:order:add']">新增</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['device:order:edit']">修改</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['device:order:remove']">删除</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['device:order:export']">导出</el-button>-->
<!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="orderList" border="true">
        <el-table-column type="index" width="55" align="center" label="#" fixed="left"/>
        <el-table-column label="订单编号" align="center" prop="orderNo" width="185" fixed="left"/>
        <el-table-column label="手机号码" align="center" prop="phone" width="120"/>
        <el-table-column label="设备号" align="center" prop="deviceNo" width="180" show-overflow-tooltip="true"/>
        <el-table-column label="设备名称" align="center" prop="deviceName" width="180"  />
        <el-table-column label="柜号" align="center" prop="deviceGridName" />
        <el-table-column label="开锁密码" align="center" prop="openPwd" width="120"/>
        <el-table-column label="用户ID" align="center" prop="userId" v-if="false"/>
        <el-table-column label="订单ID" align="center" prop="orderId" v-if="false" />
        <el-table-column label="订单状态" align="center" prop="orderStatus" width="90">
          <template #default="scope">
            <dict-tag :options="order_status" :value="scope.row.orderStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="押金状态" align="center" prop="orderStatus" width="90">
          <template #default="scope">
            <dict-tag :options="refund_status" :value="scope.row.refundStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="开锁密码" align="center" prop="openPwd" v-if="false"/>
        <el-table-column label="场地名称" align="center" prop="positionName" />
        <el-table-column label="交易号" align="center" prop="transactionNo" show-overflow-tooltip="true"/>
        <el-table-column label="支付金额" align="center" prop="payAmount" />
        <el-table-column label="预付金额" align="center" prop="prestoreDeviceAmount" />
        <el-table-column label="押金金额" align="center" prop="depositAmount" />
        <el-table-column label="存柜金额" tooltip-effect="tooltip-effect" align="center" prop="actualDeviceAmount" />
        <el-table-column label="订单余额" align="center" prop="residueAmount" />
        <el-table-column label="开始时间" align="center" prop="startTime" width="155">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="155">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="身份证" align="center" prop="idNo" width="200"/>
        <el-table-column label="交易完成时间" align="center" prop="successTime" width="155">
          <template #default="scope">
            <span>{{ parseTime(scope.row.successTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付时间" align="center" prop="payTime" width="155">
          <template #default="scope">
            <span>{{ parseTime(scope.row.payTime) }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column label="是否转余额" align="center" prop="isToBalance" width="150"/>-->
<!--        <el-table-column label="offline 离线  online 在线" align="center" prop="isOffline" />-->
        <el-table-column label="计费类型" align="center" prop="orderType">
          <template #default="scope">
            <dict-tag :options="order_type" :value="scope.row.orderType"/>
          </template>
        </el-table-column>
        <el-table-column label="结算状态" align="center" prop="settlementStatus" width="90">
          <template #default="scope">
            <dict-tag :options="order_settlement_status" :value="scope.row.settlementStatus"/>
          </template>
        </el-table-column>
<!--        <el-table-column label="支付方式" align="center" prop="payWay">-->
<!--          <template #default="scope">-->
<!--            <dict-tag :options="pay_way" :value="scope.row.payWay"/>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="备注" align="center" prop="remark" width="150" show-overflow-tooltip="true"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
          <template #default="scope">
<!--            <el-tooltip content="修改" placement="top">-->
<!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:order:edit']"></el-button>-->
<!--            </el-tooltip>-->
<!--            <el-tooltip content="删除" placement="top">-->
<!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:order:remove']"></el-button>-->
<!--            </el-tooltip>-->

            <el-button link type="primary" icon="CircleCheck" @click="withdraw(scope.row)" :disabled="scope.row.orderStatus != 'used_done' || scope.row.refundStatus != 'refund_no'">提现</el-button>
            <el-button link type="primary" icon="CircleCheck" @click="handleEndOrder(scope.row)" :disabled="scope.row.orderStatus != 'in_used'">结束订单</el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <!-- 结束订单弹框 -->
    <el-dialog title="结束订单" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="endOrderFormRef" :model="endOrderForm" :rules="endOrderRules" label-width="80px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="endOrderForm.orderNo" disabled />
        </el-form-item>
        <el-form-item label="是否开锁" prop="isNeedOpen">
          <el-radio-group v-model="endOrderForm.isNeedOpen" class="ml-4">
            <el-radio label="true" size="large">开锁</el-radio>
            <el-radio label="false" size="large">不开锁</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="endOrdersubmitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order" lang="ts">
import {listOrder, getOrder, delOrder, addOrder, updateOrder, withdrawOrder, endOrder} from '@/api/device/order';
import { OrderVO, OrderQuery, OrderForm } from '@/api/device/order/types';
import {$ref} from "vue/macros";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_status, order_type, pay_way,refund_status,order_settlement_status } = toRefs<any>(proxy?.useDict('order_status', 'order_type', 'pay_way','refund_status','order_settlement_status'));

const orderList = ref<OrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const orderFormRef = ref<ElFormInstance>();
const endOrderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrderForm = {
  orderId: undefined,
  userId: undefined,
  phone: undefined,
  deviceNo: undefined,
  deviceGridId: undefined,
  openPwd: undefined,
  orderNo: undefined,
  positionId: undefined,
  transactionNo: undefined,
  payAmount: undefined,
  prestoreDeviceAmount: undefined,
  depositAmount: undefined,
  actualDeviceAmount: undefined,
  residueAmount: undefined,
  startTime: undefined,
  endTime: undefined,
  orderStatus: undefined,
  idNo: undefined,
  successTime: undefined,
  payTime: undefined,
  isToBalance: undefined,
  isOffline: undefined,
  orderType: undefined,
  payWay: undefined,
  remark: undefined,
  refundStatus: undefined
}
const data = reactive<PageData<OrderForm, OrderQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 'create_time',
    isAsc: 'desc',
    userId: undefined,
    deviceName: undefined,
    deviceGridName: undefined,
    phone: undefined,
    deviceNo: undefined,
    deviceGridId: undefined,
    openPwd: undefined,
    orderNo: undefined,
    positionId: undefined,
    transactionNo: undefined,
    payAmount: undefined,
    prestoreDeviceAmount: undefined,
    depositAmount: undefined,
    actualDeviceAmount: undefined,
    residueAmount: undefined,
    startTime: undefined,
    endTime: undefined,
    orderStatus: undefined,
    idNo: undefined,
    successTime: undefined,
    payTime: undefined,
    isToBalance: undefined,
    isOffline: undefined,
    orderType: undefined,
    payWay: undefined,
    refundStatus: undefined,
    settlementStatus: undefined,
    params: {
    }
  },

   endOrderForm : {
    orderNo: undefined,
    isNeedOpen: undefined,
  },


  endOrderRules: {
    isNeedOpen: [
      { required: true, message: "是否开锁选项不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form , endOrderRules, endOrderForm} = toRefs(data);


/** 提交按钮 */
const endOrdersubmitForm = () => {
  endOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await endOrder(endOrderForm.value.orderNo,endOrderForm.value.isNeedOpen).finally(() =>  buttonLoading.value = false);
      proxy?.$modal.msgSuccess("处理成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 查询订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrder(queryParams.value);
  orderList.value = res.data.records;
  total.value = res.data.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  orderFormRef.value?.resetFields();
  endOrderFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderVO[]) => {
  ids.value = selection.map(item => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加订单";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: OrderVO) => {
  reset();
  const _orderId = row?.orderId || ids.value[0]
  const res = await getOrder(_orderId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改订单";
}

/** 提交按钮 */
const submitForm = () => {
  orderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.orderId) {
        await updateOrder(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addOrder(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: OrderVO) => {
  const _orderIds = row?.orderId || ids.value;
  await proxy?.$modal.confirm('是否确认删除订单编号为"' + _orderIds + '"的数据项？').finally(() => loading.value = false);
  await delOrder(_orderIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/**
 * 提现操作
 * @param row
 */
const withdraw = async (row?: OrderVO) => {
  const orderNo = row.orderNo;
  const userId = row.userId;
  await proxy?.$modal.confirm('是否确认将订单编号为: ' + orderNo + '的余额' +row.residueAmount + '元提现？').finally(() => loading.value = false);
  await withdrawOrder(orderNo,userId);
  proxy?.$modal.msgSuccess("提现成功");
  await getList();
}

const handleEndOrder = async (row?: OrderVO) => {
  reset();
  console.log("row.orderNo",row.orderNo);
  endOrderForm.value.orderNo = row.orderNo;
  dialog.visible = true;
  buttonLoading.value = false;
}



/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('device/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
